use super::Language_Parser;
use colored::Colorize;
use std::fs;
use tree_sitter::Parser;

pub struct Rust_Parser {}

impl Language_Parser for Rust_Parser {
    fn filter(&self, file_name: &String) -> bool {
        file_name.ends_with(".rs")
    }

    fn get_tree_sitter(&self) -> Parser {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_rust::LANGUAGE.into())
            .expect("tree-sitter-go not exists");
        return parser;
    }

    fn find_functions(&self, file_path: String) -> Vec<String> {
        let mut parser = self.get_tree_sitter();

        // 读取代码
        let content = fs::read_to_string(&file_path.as_str()).expect("java file not exists");
        let content = content.as_str();

        // 解析
        let java_tree = parser.parse(content, None).unwrap();

        // 遍历查找
        let mut funcs: Vec<String> = Vec::new();
        let root_node: tree_sitter::Node<'_> = java_tree.root_node();
        let mut cursor: tree_sitter::TreeCursor<'_> = root_node.walk();
        cursor.goto_first_child();
        'outer: loop {
            let current_node = cursor.node();
            // let func_code = &content[current_node.start_byte()..current_node.end_byte()];
            // println!("{} {}", current_node.kind().red(), func_code);
            if current_node.kind() == "function_item" {
                let func_code = &content[current_node.start_byte()..current_node.end_byte()];
                funcs.push(func_code.to_string());
            }

            if cursor.goto_first_child() {
                continue;
            }

            if cursor.goto_next_sibling() {
                continue;
            }

            loop {
                if !cursor.goto_parent() {
                    break 'outer;
                }

                if !cursor.goto_next_sibling() {
                    continue;
                }
                break;
            }

            continue;
        }

        return funcs;
    }
}

#[test]
fn test() {
    let funcs = Rust_Parser {}.find_functions("assets/test_src/rust.rs".to_string());
    println!("{}", funcs.len())
}
